package tools

import (
	"bufio"
	"container/list"
	"fmt"
	"github.com/fwhezfwhez/errorx"
	"github.com/spf13/viper"
	"io"
	"os"
	"strings"
)

func ReadConfigFile(path string) (map[string]interface{}, error) {
	if !PathExists(path) {
		return nil, fmt.Errorf("路径[%s]不存在", path)
	}
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if nil != err {
		return nil, errorx.New(err)
	}
	allKeys := viper.AllKeys()

	allMaps := make(map[string]interface{}, len(allKeys))

	for _, key := range allKeys {
		allMaps[key] = viper.Get(key)
	}
	return allMaps, nil
}

//PathExists 判断文件夹是否存在
func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

//ReadLine按行读文件
func ReadLine(filePth string) (*list.List, error) {
	f, err := os.Open(filePth)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = f.Close()
	}()

	bfRd := bufio.NewReader(f)
	lines := list.New()
	for {
		line, err := bfRd.ReadBytes('\n')
		if err == io.EOF {
			err = nil
			break
		} else if err != nil {
			break
		}
		lines.PushBack(line)
	}
	return lines, err
}

//FileExit 文件是否存在
func FileExit(file string) bool {
	_, err := os.Lstat(file)
	return !os.IsNotExist(err)
}

func DealPath(path, replace string) string {

	path = strings.ReplaceAll(path, "<", replace)
	path = strings.ReplaceAll(path, ">", replace)
	path = strings.ReplaceAll(path, "/", replace)
	path = strings.ReplaceAll(path, "\\", replace)
	path = strings.ReplaceAll(path, "|", replace)
	path = strings.ReplaceAll(path, "?", replace)
	path = strings.ReplaceAll(path, "*", replace)
	path = strings.ReplaceAll(path, "%", replace)
	path = strings.ReplaceAll(path, "/", replace)
	path = strings.ReplaceAll(path, ":", replace)
	path = strings.ReplaceAll(path, "\"", replace)
	path = strings.ReplaceAll(path, "\r", "")
	path = strings.ReplaceAll(path, "\n", "")
	return path
}
